import React, { useEffect, useState } from "react";
import { Button, Form, Input, Tree } from "antd";
import { mainRoutes } from "@/router";
import { rolePost, rolePut, RoleType } from "@/api/user";
import { useForm } from "antd/es/form/Form";

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

/* eslint-disable no-template-curly-in-string */
const validateMessages = {
  required: "${label} is required!",
  types: {
    email: "${label} is not a valid email!",
    number: "${label} is not a valid number!",
  },
  number: {
    range: "${label} must be between ${min} and ${max}",
  },
};
/* eslint-enable no-template-curly-in-string */
interface RoleFormPropsType {
  initData: RoleType | null; //表单初始数据包
  handleRoleList: (roleObj: RoleType) => void;
}
const RoleForm: React.FC<RoleFormPropsType> = (props) => {
  const [form] = useForm();
  const [checkedKeys, setCheckedKeys] = useState<Array<string>>([]);
  const [halfKeys, setHalfKeys] = useState<Array<string>>([]);
  const handleTreeCheck = (checkedKeyList: any, { halfCheckedKeys }: any) => {
    console.log(checkedKeyList, halfCheckedKeys);
    setCheckedKeys(checkedKeyList); //记录勾选的菜单
    setHalfKeys(halfCheckedKeys); //记录半选的菜单
  };
  const onFinish = (values: RoleType) => {
    values.checkedKeys = checkedKeys;
    values.halfCheckedKeys = halfKeys;
    console.log(values);
    if (props.initData) {
      let { objectId } = props.initData;
      rolePut(objectId, values); //更新
      props.handleRoleList({ ...values, objectId });
    } else {
      rolePost(values).then((res) => {
        values.objectId = res.data.objectId;
        props.handleRoleList(values);
      }); //新增
    }
  };
  useEffect(() => {
    console.log("RoleForm的useEffect执行了");
    if (props.initData) {
      form.setFieldsValue(props.initData);
      let { checkedKeys, halfCheckedKeys } = props.initData;
      setCheckedKeys(checkedKeys);
    } else {
      form.resetFields();
      setCheckedKeys([]);
    }
  }, [props.initData]);
  return (
    <Form
      {...layout}
      name="nest-messages"
      onFinish={onFinish}
      form={form}
      style={{ maxWidth: 600 }}
      validateMessages={validateMessages}
    >
      <Form.Item name="roleName" label="角色名称" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item name="tree" label="菜单权限">
        <Tree
          checkable
          treeData={mainRoutes}
          checkedKeys={checkedKeys}
          onCheck={handleTreeCheck}
        />
      </Form.Item>

      <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
        <Button type="primary" htmlType="submit">
          {props.initData ? "修改角色" : "新增角色"}
        </Button>
      </Form.Item>
    </Form>
  );
};

export default RoleForm;
